package com.foo.example.action;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

import com.foo.common.base.action.FooGenericAction;
import com.foo.common.base.pojo.FooGenericSearch;
import com.foo.common.base.pojo.FooGenericSearchResult;
import com.foo.common.base.pojo.FooGenericTransactionModel;
import com.foo.common.base.pojo.FooJob;
import com.foo.common.base.utils.FooUtils;
import com.foo.example.model.Foo;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;

public class HelloAction extends FooGenericAction { // 模型驱动
	private static final long serialVersionUID = 1L;

	@Override
	public String execute() throws Exception {
		System.out.println("test");
		// Foo attachTree1 = new Foo();
		// Foo attachTree2 = new Foo();
		// fooService.save(attachTree1, attachTree2);
		// logger.info("You get last size of" + fooService.findAll().size());
		// System.out.println(fooService.findAll().size());
		// logger.info(fooSpringJdbcService
		// .queryForInt("select count(0) from attachTree where text='123' ")
		// + "");
		return "success";
	}

	/**
	 * 分页查询1：普通分页查询，不使用拦截器
	 * 
	 * @throws SchedulerException
	 */
	@org.apache.struts2.convention.annotation.Action("/example/getAjaxData")
	public void getAjaxData() throws IOException, SchedulerException {

		Map<String, Object> myMap = Maps.newHashMap();

		SchedulerFactory schedFact = (SchedulerFactory) request.getSession()
				.getServletContext()
				.getAttribute("org.quartz.impl.StdSchedulerFactory.KEY");

		System.out.println(schedFact.getScheduler().isStarted());

		FooGenericSearch search = new FooGenericSearch();
		search.setQueryHql(" from Foo");
		search.setCountHql(" select count(*) from Foo");
		List<?> myList = null;
		FooGenericSearchResult fooGenericSearchResult = null;

		if (Strings.nullToEmpty(request.getParameter("bNeedPaging")).equals(
				"false")) {
			fooGenericSearchResult = fooGenericService.list(search);
			myList = fooGenericSearchResult.getResult();
			myMap.put("aaData", myList);
			int myCount = fooGenericSearchResult.getTotalCount();
			myMap.put("iTotalRecords", myCount);
			myMap.put("iTotalDisplayRecords", myCount);
		} else {
			String iDisplayLength = request.getParameter("iDisplayLength");
			String iDisplayStart = request.getParameter("iDisplayStart");
			search.setFirstResult(Integer.parseInt(iDisplayStart));
			search.setMaxResults(Integer.parseInt(iDisplayLength));
			FooGenericSearchResult searchResult = fooGenericService
					.searchAndCount(search);
			myList = searchResult.getResult();
			myMap.put("aaData", myList);
			myMap.put("iTotalRecords", searchResult.getTotalCount());
			myMap.put("iTotalDisplayRecords", searchResult.getTotalCount());
		}
		FooUtils.printJsonObjectSerializeNulls(response, myMap);
		// System.out.println("Add test");
		// Foo myFoo = new Foo();
		// Search mySearch = new Search();
		// mySearch.setSearchClass(Foo.class);
		// mySearch.addFilterEqual("id", "2c9e9d86343ae29801343ae2b30c0001");
		// myFoo = fooService.searchUnique(mySearch);
		// myFoo.setText("123456");
		// fooService.save(myFoo);
		// System.out.println("Remove test");
		// Foo myFoo = new Foo();
		// myFoo.setId("2c9e9d86343ae29801343ae2b30c0001");
		// fooService.remove(myFoo);
	}

	/**
	 * 新增
	 */
	public void add() throws IOException {
		String text = request.getParameter("text");
		String href = request.getParameter("href");
		System.out.println(text);
		System.out.println(href);
		FooUtils.printJsonSuccessMsg(response);
	}

	@org.apache.struts2.convention.annotation.Action("/testSave")
	public void testSave() throws IOException {
		System.out.println("123");
		fooGenericService.doInTransaction(new FooGenericTransactionModel() {
			@Override
			public void execute() {
				fooGenericService.save(new Foo());
				// throw new RuntimeException();
			}
		});
		FooUtils.printJsonSuccessMsg(response);
	}

	public void testQuartzJob() throws IOException, SchedulerException {
		// define the job and tie it to our HelloJob class
		SchedulerFactory schedFact = (SchedulerFactory) request.getSession()
				.getServletContext()
				.getAttribute("org.quartz.impl.StdSchedulerFactory.KEY");
		FooUtils.log(schedFact.getScheduler().isStarted());

		JobDataMap jobDataMap = new JobDataMap();
		jobDataMap.put("id", "myJobPk");
		JobDetail jobDetail = JobBuilder.newJob(FooJob.class)
				.withIdentity("myJob", "group1").usingJobData(jobDataMap)
				.build();

		Trigger trigger = TriggerBuilder
				.newTrigger()
				.withIdentity("trigger3", "group1")
				.withSchedule(
						CronScheduleBuilder.cronSchedule("0/10 * * * * ?"))
				.forJob(jobDetail).build();

		Scheduler scheduler = schedFact.getScheduler();
		scheduler.deleteJob(new JobKey("myJob", "group1"));
		scheduler.scheduleJob(jobDetail, trigger);
	}

	public static void main(String[] args) {
		try {
			// Grab the Scheduler instance from the Factory
			Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

			// and start it off
			scheduler.start();

			JobDataMap jobDataMap = new JobDataMap();
			jobDataMap.put("id", "myJobPk");
			JobDetail jobDetail = JobBuilder.newJob(FooJob.class)
					.withIdentity("myJob", "group1").usingJobData(jobDataMap)
					.build();

			Trigger trigger = TriggerBuilder
					.newTrigger()
					.withIdentity("trigger3", "group1")
					.withSchedule(
							CronScheduleBuilder.cronSchedule("0/10 * * * * ?"))
					.forJob(jobDetail).build();

			scheduler.scheduleJob(jobDetail, trigger);
			// scheduler.deleteJob(new JobKey("myJob", "group1"));

			scheduler.shutdown(true);

		} catch (SchedulerException se) {
			se.printStackTrace();
		}
	}
}
